package zhtt;

import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;

import java.util.Iterator;
import java.util.List;

/**
 * Created by zhtt on 2017/4/10.
 */
public class JunitTest_list_iterate {

    private Session session;

    @Before
    public void setUp(){
        session=HbnUtil.getSession();
    }

    @Test
    /**
     * list查询未启用缓存
     */
    public void list(){
        try{
            String hql="from Student";
            session.beginTransaction();
            List<Student> studentList1=session.createQuery(hql).list();
            System.out.println(studentList1);

            List<Student> studentList2=session.createQuery(hql).list();
            System.out.println(studentList2);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    /**
     * interate查询启用缓存
     */
    public void interate(){
       try{
           String hql="from Student";
           session.beginTransaction();
           Iterator<Student> studentList1=session.createQuery(hql).iterate();
           System.out.println(studentList1);

           Iterator<Student> studentList2=session.createQuery(hql).iterate();
           System.out.println(studentList2);
           session.getTransaction().commit();
       }catch (Exception e){
           e.printStackTrace();
       }
    }

    @Test
    /**
     * 避免n+1问题
     * 第一次list查询、第二次查询用iterate
     */
    public void list_iterate(){
        try{
            String hql="from Student";
            session.beginTransaction();
            List<Student> studentList1=session.createQuery(hql).list();
            System.out.println(studentList1);

            Iterator<Student> studentList2=session.createQuery(hql).iterate();
            System.out.println(studentList2);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
